﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Quadarax.Applications.ASMIDE.Controls
{
    class QTextCache
    {
        public enum eSegmentStatus
        {
            enssNone,            
            enssRead,
            enssChanged     
        }

        protected long m_nFileSegmentPosition = 0;
        protected long m_nFileSegmentLength = 0;
        protected char[] m_aSegment = null;
        protected long m_nSegmentPosition = 0;
        protected long m_nSegmentLength = 0;
        protected long m_nStartLine = 0;
        protected long m_nEndLine = 0;        
        protected bool m_bEndLineContignous = false;


        protected QTextCacheCollection m_oParent;

        protected eSegmentStatus m_eStatus = eSegmentStatus.enssNone;

        public long SegmentPosition { get { return m_nSegmentPosition; } }
        public long SegmentLength { get { return m_nSegmentLength; } }
        public char[] Data { get { CheckData(); return m_aSegment; } }
        public eSegmentStatus Status { get { return m_eStatus; } }
        public long StartLine { get { return m_nStartLine; } }
        public long EndLine { get { return m_nEndLine; } }

        public QTextCache(QTextCacheCollection oParent,long nInitialPostion, long nInitialLength)
        {
            m_oParent = oParent;
            m_nFileSegmentLength = nInitialLength;
            m_nFileSegmentPosition = nInitialPostion;
            m_nSegmentPosition = nInitialPostion;
            m_eStatus = eSegmentStatus.enssNone;
        }

        public void Read()
        {            
            m_aSegment = new char[m_nFileSegmentLength];
            StreamReader oReader = new StreamReader(m_oParent.GetStream());
            oReader.BaseStream.Seek(m_nFileSegmentPosition, SeekOrigin.Begin);
            oReader.ReadBlock(m_aSegment, 0, Convert.ToInt32(m_nFileSegmentLength));            
            m_eStatus = eSegmentStatus.enssRead;
        }

        private void CheckData()
        {
            if (m_eStatus == eSegmentStatus.enssNone)
                Read();            
        }

        public long GetDataLength()
        {
            if (m_aSegment != null)
                return m_aSegment.Length;
            else
                return -1;
        }
    }
}
